<template>
  <basic-container>
    <el-tabs v-model="tabsIndex" @tab-click="handleTabClick(tabsIndex)" style="margin: 0 10px">
      <el-tab-pane label="不良类型" name="4">
        <avue-crud
          v-if="tabsIndex === '4'"
          ref="failureCodeCrud"
          :table-loading="loading"
          v-model="failureTypeModel"
          :data="failureTypeData"
          :option="failureTypeOption"
          :page.sync="page"
          :search.sync="query"
          :permission="repairCodePermissionList"
          :before-open="beforeOpen"
          @row-update="rowUpdate"
          @row-save="rowSave"
          @row-del="rowDel"
          @search-change="searchChange"
          @search-reset="searchReset"
          @selection-change="selectionChange"
          @current-change="currentChange"
          @size-change="sizeChange"
          @refresh-change="refreshChange"
          @on-load="onLoad"
        >
          <template slot="menuLeft">
            <el-button v-if="permission.failureconfig_repairCodeDelete" type="danger" size="small" icon="el-icon-delete" @click="handleDelete()">删 除</el-button>
            <el-button v-if="permission.failureconfig_repairCodeImport" type="success" size="small" icon="el-icon-upload2" @click="failureTypeImport">导 入</el-button>
            <el-button type="primary" @click="$refs.failureType.visible = true" icon="el-icon-download" size="small">导出</el-button>
          </template>
        </avue-crud>
      </el-tab-pane>
      <el-tab-pane label="不良现象" name="1">
        <avue-crud
          v-if="tabsIndex === '1'"
          ref="failureCodeCrud"
          :table-loading="loading"
          v-model="failureCodeModel"
          :data="failureCodeData"
          :option="failureCodeOption"
          :page.sync="page"
          :search.sync="query"
          :permission="permissionList"
          :before-open="beforeOpen"
          @row-update="rowUpdate"
          @row-save="rowSave"
          @row-del="rowDel"
          @search-change="searchChange"
          @search-reset="searchReset"
          @selection-change="selectionChange"
          @current-change="currentChange"
          @size-change="sizeChange"
          @refresh-change="refreshChange"
          @on-load="onLoad"
        >
          <template slot="menuLeft">
            <el-button v-if="permission.failureconfig_failureCodeDelete" type="danger" size="small" icon="el-icon-delete" @click="handleDelete()">删 除</el-button>
            <el-button v-if="permission.failureconfig_failureCodeImport" type="success" size="small" icon="el-icon-upload2" @click="failureCodeImport">导 入</el-button>
            <el-button type="primary" @click="$refs.exportCompCode.visible = true" size="small" icon="el-icon-download">导出</el-button>
          </template>
          <template slot="parentCodeSearch">
            <el-input placeholder="请选择 不良类型代码" v-model="query.parentCode" clearable>
              <el-button slot="append" icon="el-icon-search" @click="openFailureTypeCommonModal('search')"></el-button>
            </el-input>
          </template>
        </avue-crud>
      </el-tab-pane>
      <el-tab-pane label="不良原因" name="2">
        <avue-crud
          v-if="tabsIndex === '2'"
          ref="failureCodeCrud"
          :table-loading="loading"
          v-model="failureCauseModel"
          :data="failureCauseData"
          :option="failureCauseOption"
          :page.sync="page"
          :search.sync="query"
          :before-open="beforeOpen"
          @row-update="rowUpdate"
          @row-save="rowSave"
          @row-del="rowDel"
          @search-change="searchChange"
          @search-reset="searchReset"
          @selection-change="selectionChange"
          @current-change="currentChange"
          @size-change="sizeChange"
          @refresh-change="refreshChange"
          @on-load="onLoad"
        >
          <template slot="menuLeft">
            <el-button v-if="permission.failureconfig_failureCauseAdd" type="primary" size="small" icon="el-icon-plus" @click="handleAddBtn()"> 新 增 </el-button>
            <el-button v-if="permission.failureconfig_failureCauseDelete" type="danger" size="small" icon="el-icon-delete" @click="handleDelete()">删 除</el-button>
            <el-button v-if="permission.failureconfig_failureCauseImport" type="success" size="small" icon="el-icon-upload2" @click="failureCauseImport">导 入</el-button>
            <el-button type="primary" @click="$refs.exportCompCause.visible = true" size="small" icon="el-icon-download">导出</el-button>
          </template>

          <template slot-scope="{ row }" slot="menu">
            <el-button v-if="permission.failureconfig_failureCauseView" type="text" icon="el-icon-view" size="small" @click.stop="handleView(row)">详情 </el-button>
            <el-button v-if="permission.failureconfig_failureCauseEdit" type="text" icon="el-icon-edit" size="small" @click.stop="handleEdit(row)">编辑 </el-button>
            <el-button v-if="permission.failureconfig_failureCauseDelete" type="text" size="small" icon="el-icon-delete" @click.stop="rowDel(row)">删除 </el-button>
          </template>
        </avue-crud>
      </el-tab-pane>
      <!--      <el-tab-pane label="维修代码" name="3">-->
      <!--        <avue-crud-->
      <!--          v-if="tabsIndex === '3'"-->
      <!--          ref="failureCodeCrud"-->
      <!--          :table-loading="loading"-->
      <!--          v-model="repairCodeModel"-->
      <!--          :data="repairCodeData"-->
      <!--          :option="repairCodeOption"-->
      <!--          :page.sync="page"-->
      <!--          :search.sync="query"-->
      <!--          :before-open="beforeOpen"-->
      <!--          @row-update="rowUpdate"-->
      <!--          @row-save="rowSave"-->
      <!--          @row-del="rowDel"-->
      <!--          @search-change="searchChange"-->
      <!--          @search-reset="searchReset"-->
      <!--          @selection-change="selectionChange"-->
      <!--          @current-change="currentChange"-->
      <!--          @size-change="sizeChange"-->
      <!--          @refresh-change="refreshChange"-->
      <!--          @on-load="onLoad"-->
      <!--        >-->
      <!--          <template slot="menuLeft">-->
      <!--            <el-button v-if="permission.failureconfig_repairCodeDelete" type="danger" size="small" icon="el-icon-delete" @click="handleDelete()">删 除</el-button>-->
      <!--            <el-button v-if="permission.failureconfig_repairCodeImport" type="success" size="small" icon="el-icon-upload2" @click="repairCodeImport">导 入</el-button>-->
      <!--            <el-button type="primary" @click="$refs.exportCompRepair.visible = true" icon="el-icon-download" size="small">导出</el-button>-->
      <!--          </template>-->
      <!--        </avue-crud>-->
      <!--      </el-tab-pane>-->
    </el-tabs>
    <el-dialog append-to-body :close-on-click-modal="false" :title="title" :visible.sync="showDialog" v-if="showDialog" width="60%" top="5vh">
      <div v-loading="failureCauseLoading">
        <div class="avue-group__header avue-group">
          <i class="el-icon-vertical-bar avue-group__icon"></i>
          <h1 class="avue-group__title">不良原因大类</h1>
        </div>
        <avue-form ref="properties" v-model="properties" :option="propertiesOption"></avue-form>
        <div class="avue-group__header avue-group">
          <i class="el-icon-vertical-bar avue-group__icon"></i>
          <h1 class="avue-group__title">不良原因小类</h1>
        </div>
        <avue-crud ref="failureSubclassCrud" :option="failureSubclassOption" v-model="failureSubclassModel" :table-loading="loading" :data="failureSubclassData">
          <template slot="menuLeft">
            <el-button type="primary" size="small" icon="el-icon-plus" v-if="isNone !== 'none'" @click="addCellRow()">新增小类</el-button>
          </template>
          <template slot="menu" slot-scope="{ row }">
            <el-button type="text" size="small" icon="el-icon-delete" @click="rowSubclassDel(row)">删除</el-button>
          </template>
        </avue-crud>
      </div>

      <span slot="footer" class="dialog-footer" :style="{ display: isNone }">
        <el-button size="small" icon="el-icon-circle-close" @click="showDialog = false">取 消</el-button>
        <el-button type="primary" size="small" :icon="title == '新增' || title == '添加不良原因' ? 'el-icon-circle-plus-outline' : 'el-icon-circle-check'" @click="submit">{{
          title == '新增' || title == '添加不良原因' ? '提 交' : '提 交'
        }}</el-button>
      </span>
    </el-dialog>
    <el-dialog xportConfig.optiontitle="不良现象导入" append-to-body :visible.sync="failureCodeExcelBox" width="555px">
      <avue-form v-if="failureCodeExcelBox" :option="failureCodeExcelOption" v-model="failureCodeExcelForm" :upload-after="uploadAfter">
        <template slot="excelTemplate">
          <el-button type="primary" class="el-icon-download el-icon--right" @click="handleTemplate('failureCodeExcelBox')">模板下载 </el-button>
        </template>
      </avue-form>
    </el-dialog>
    <el-dialog title="维修代码导入" append-to-body :visible.sync="repairCodeExcelBox" width="555px">
      <avue-form v-if="repairCodeExcelBox" :option="repairCodeExcelOption" v-model="repairCodeExcelForm" :upload-after="repairCodeUploadAfter">
        <template slot="excelTemplate">
          <el-button type="primary" class="el-icon-download el-icon--right" @click="handleTemplate('repairCodeExcelBox')">模板下载 </el-button>
        </template>
      </avue-form>
    </el-dialog>
    <el-dialog title="不良原因导入" append-to-body :visible.sync="failureCauseExcelBox" width="555px">
      <avue-form v-if="failureCauseExcelBox" :option="failureCauseExcelOption" v-model="failureCauseExcelForm" :upload-after="failureCauseUploadAfter">
        <template slot="excelTemplate">
          <el-button type="primary" class="el-icon-download el-icon--right" @click="handleTemplate('failureCauseExcelBox')"> 模板下载 </el-button>
        </template>
      </avue-form>
      <!--      <avue-form v-if="failureCauseExcelBox" :option="failureCauseExcelOption2" v-model="failureCauseExcelForm2" :upload-after="failureCauseUploadAfter">-->
      <!--        <template slot="excelTemplate">-->
      <!--          <el-button type="primary" class="el-icon-download el-icon&#45;&#45;right" @click="handleTemplate('failureCauseExcelBox2')"> 模板下载 </el-button>-->
      <!--        </template>-->
      <!--      </avue-form>-->
    </el-dialog>
    <el-dialog title="不良类型导入" append-to-body :visible.sync="failureTypeExcelBox" width="555px">
      <avue-form v-if="failureTypeExcelBox" :option="failureTypeExcelOption" v-model="failureTypeExcelForm" :upload-after="failureTypeUploadAfter">
        <template slot="excelTemplate">
          <el-button type="primary" class="el-icon-download el-icon--right" @click="handleTemplate('failureTypeExcelBox')">模板下载 </el-button>
        </template>
      </avue-form>
    </el-dialog>
    <export-comp ref="exportCompCode" page-api-url="mes-product/mro-dict/page" :option="failureCodeOption" :page="page" :query="query" file-name="不良现象"></export-comp>
    <export-comp ref="exportCompCause" page-api-url="mes-product/mro-dict/page" :option="failureCauseOption" :page="page" :query="query" file-name="不良原因"></export-comp>
    <export-comp ref="exportCompRepair" page-api-url="mes-product/mro-dict/page" :option="repairCodeOption" :page="page" :query="query" file-name="维修代码"></export-comp>
    <export-comp ref="failureType" page-api-url="mes-product/mro-dict/page" :option="failureTypeOption" :page="page" :query="query" file-name="不良类型"></export-comp>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, getWorkstationRouteList, exprot, checkCode } from '@/api/repair/failureconfig';
import { mapGetters } from 'vuex';
import { getToken } from '@/util/auth';
import exportComp from '@/components/export-comp';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';

export default {
  components: {
    exportComp,
    CommonModalTemplate
  },
  data() {
    var obj = {
      calcHeight: 30,
      tip: false,
      searchShow: true,
      // searchMenuSpan: 6,
      border: true,
      index: true,
      dialogWidth: '20%',
      indexLabel: '序号',
      viewBtn: true,
      selection: true,
      labelWidth: '110',
      dialogClickModal: false
    };
    return {
      isPassVaildator: true,
      tabObj: {
        1: '不良现象',
        2: '不良原因',
        3: '维修代码',
        4: '不良类型'
      },
      tableOption: {},
      timer: null,
      modalName: '',
      failureCauseLoading: false,
      failureTypeExcelBox: false,
      failureTypeExcelForm: {},
      properties: {},
      failureCodeModel: {},
      failureCauseModel: {},
      repairCodeModel: {},
      failureSubclassModel: {},
      failureTypeModel: {},
      query: {},
      loading: false,
      showDialog: false,
      failureCauseId: '',
      isNone: '',
      title: '',
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      tabsIndex: '4',
      selectionList: [],
      failureCodeData: [],
      failureCauseData: [],
      repairCodeData: [],
      failureSubclassData: [],
      failureTypeData: [],
      failureCodeOption: {
        height: 'calc(100vh - 493px)',
        ...obj,
        viewTitle: '不良现象详情',
        viewBtnText: '详情',
        searchMenuPosition: 'right',
        searchMenuSpan: 24,
        dialogWidth: '40%',
        searchLabelWidth: 130,
        dialogCustomClass: 'dialog_failure_config',
        column: [
          {
            label: '不良现象代码',
            prop: 'code',
            search: true,
            // row: true,
            // span: 24,
            rules: [
              {
                required: true,
                message: '请输入不良代码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '不良现象',
            prop: 'name',
            search: true,
            searchLabelWidth: 150,
            rules: [
              {
                required: true,
                message: '请输入不良现象描述',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '不良类型代码',
            prop: 'parentCode',
            search: true,
            type: 'search',
            appendClick: () => {
              this.openFailureTypeCommonModal('');
            },
            disabled: true
          },
          {
            label: '不良类型',
            prop: 'parentName',
            search: true,
            disabled: true
          }
          // {
          //   label: '工序',
          //   prop: 'workstationRoute',
          //   row: true,
          //   span: 24,
          //   type: 'select',
          //   hide: true,
          //   search: true,
          //   formslot: true,
          //   // formatter: (val, value, label) => {
          //   //   return val.stationName;
          //   // },
          //   rules: [
          //     {
          //       required: true,
          //       message: '请选择不良工序',
          //       trigger: 'blur'
          //     }
          //   ]
          // },
          // {
          //   label: '工序',
          //   prop: 'stationName',
          //   editDisplay: false,
          //   addDisplay: false,
          //   viewDisplay: false,
          //   row: true,
          //   span: 24
          // }
        ]
      },
      failureCauseOption: {
        height: 'calc(100vh - 493px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        delBtn: false,
        addBtn: false,
        editBtn: false,
        selection: true,
        labelWidth: '110',
        dialogClickModal: false,
        searchLabelWidth: 130,
        searchMenuPosition: 'right',
        searchMenuSpan: 12,
        dialogCustomClass: 'dialog_failure_config',
        column: [
          {
            label: '不良原因大类编码',
            prop: 'code',
            search: true,
            rules: [
              {
                required: false,
                message: '请输入不良原因大类编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '不良原因大类名称',
            prop: 'name',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入不良原因大类名称',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      repairCodeOption: {
        height: 'calc(100vh - 493px)',
        ...obj,
        viewTitle: '维修代码详情',
        viewBtnText: '详情',
        searchMenuSpan: 12,
        searchMenuPosition: 'right',
        dialogCustomClass: 'dialog_failure_config',
        column: [
          {
            label: '维修代码',
            prop: 'code',
            search: true,
            row: true,
            span: 24,
            rules: [
              {
                required: true,
                message: '请输入维修代码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '维修动作',
            prop: 'name',
            search: true,
            span: 24,
            row: true,
            rules: [
              {
                required: true,
                message: '请输入维修动作',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      failureSubclassOption: {
        height: '300',
        ...obj,
        // cellBtn: true,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        selection: false,
        menu: true,
        refreshBtn: false,
        searchLabelWidth: '150',
        column: [
          {
            label: '不良原因小类编码',
            prop: 'code',
            cell: true,
            blur: ({ column, value }) => {
              this.validatorSubCode(value);
            },
            rules: [
              {
                required: true,
                message: '请输入不良原因小类编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '不良原因小类名称',
            prop: 'name',
            cell: true,
            rules: [
              {
                required: true,
                message: '请输入不良原因小类名称',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      failureTypeOption: {
        height: '300',
        ...obj,
        addBtn: true,
        viewBtn: true,
        selection: true,
        menu: true,
        searchMenuPosition: 'right',
        searchLabelWidth: '150',
        dialogCustomClass: 'dialog_failure_config',
        column: [
          {
            label: '不良类型代码',
            prop: 'code',
            search: true,
            row: true,
            span: 24,
            rules: [
              {
                required: true,
                message: '请输入不良类型代码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '不良类型',
            prop: 'name',
            search: true,
            row: true,
            span: 24,
            rules: [
              {
                required: true,
                message: '请输入不良类型',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      propertiesOption: {
        labelWidth: '150',
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '不良原因大类编码',
            prop: 'code',
            rules: [
              {
                required: true,
                message: '请输入不良原因大类编码',
                trigger: 'blur'
              }
            ],
            blur: ({ column, value }) => {
              this.validatorMainCode(value);
            }
          },
          {
            label: '不良原因大类名称',
            prop: 'name',
            rules: [
              {
                required: true,
                message: '请输入不良原因大类名称',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      data: [],
      failureCodeExcelBox: false,
      debugForm: {},
      failureCodeExcelForm: {},
      failureCodeExcelOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 100,
        column: [
          {
            label: '附件上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '不良代码上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data'
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: '/api/mes-product/mro-dict/bad-phenomenon/import'
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24
          }
        ]
      },
      repairCodeExcelBox: false,
      failureCauseExcelBox: false,
      repairCodeExcelOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 100,
        column: [
          {
            label: '附件上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '维修代码上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data'
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: '/api/mes-product/mro-dict/bad-repair-code/import'
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24
          }
        ]
      },
      failureTypeExcelOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 100,
        column: [
          {
            label: '附件上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '维修代码上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data'
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: '/api/mes-product/mro-dict/bad-type/import'
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24
          }
        ]
      },
      failureCauseExcelOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 100,
        column: [
          {
            label: '不良原因大类附件上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '不良原因大类上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data'
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: '/api/mes-product/mro-dict/bad-cause/import'
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24
          }
        ]
      },
      failureCauseExcelOption2: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 100,
        column: [
          {
            label: '不良原因小类附件上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '不良原因小类上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data'
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: '/api/mes-product/mro-dict/bad-cause/import'
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24
          }
        ]
      },

      repairCodeExcelForm: {},
      failureCauseExcelForm: {},
      failureCauseExcelForm2: {}
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.failureconfig_failureCodeAdd, false),
        viewBtn: this.vaildData(this.permission.failureconfig_failureCodeView, false),
        delBtn: this.vaildData(this.permission.failureconfig_failureCodeDelete, false),
        editBtn: this.vaildData(this.permission.failureconfig_failureCodeEdit, false)
      };
    },
    repairCodePermissionList() {
      return {
        addBtn: this.vaildData(this.permission.failureconfig_repairCodeAdd, false),
        viewBtn: this.vaildData(this.permission.failureconfig_repairCodeView, false),
        editBtn: this.vaildData(this.permission.failureconfig_repairCodeEdit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.structuralSplit();
    });
  },
  methods: {
    structuralSplit() {
      if ($('.informationLabel').length === 0) {
        let card = $('#app .el-card .is-never-shadow');
        let searchSon = $(card[0]).find('.avue-form');
        let searchFather = document.createElement('div');
        searchFather.className = 'informationLabel el-tabs el-tabs--top el-tabs--border-card';
        searchFather.innerHTML = `<div class="el-tabs__header is-top">
              <div class="el-tabs__content" style="padding: 10px 10px 0 10px;background-color: #ffffff;"></div>
            </div>`;
        $(searchFather).find('.el-tabs__content').append(searchSon);
        $('#app .avue-crud__search .el-card__body').append(searchFather);

        let tableSon = $(card[1]).find('.el-card__body');
        let tableFather = document.createElement('div');
        tableFather.className = 'informationLabel el-tabs el-tabs--top el-tabs--border-card';
        tableFather.innerHTML = `<div class="el-tabs__header is-top">
              <div class="el-tabs__content" style="padding: 10px 10px 0 10px;background-color: #ffffff;"></div>
            </div>`;
        $(tableFather).find('.el-tabs__content').append(tableSon);
        console.log(tableFather);
        $(card[1]).append(tableFather);
        let elCardBody = $('.basic-container__card').find('.el-card__body');
        $(elCardBody[0]).addClass('el-card__body__padding');
      }
    },
    getSelectedRows(rowData, title) {
      console.log(title);
      console.log(rowData);
      switch (this.modalName) {
        case 'failureType':
          if (title === 'search') {
            this.query.parentCode = rowData.code;
          } else {
            this.failureCodeModel.parentCode = rowData.code;
            this.failureCodeModel.parentName = rowData.name;
            this.failureCodeModel.parentId = rowData.id;
          }
          break;
      }
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    async handleTemplate(key) {
      const exportKeyMap = {
        failureCodeExcelBox: '不良现象导入模板.xlsx', //不良现象,
        repairCodeExcelBox: '维修代码导入模板.xlsx', //维修代码,
        failureCauseExcelBox: '不良原因大类导入模板.xlsx', //不良原因大类,
        failureCauseExcelBox2: '不良原因小类导入模板.xlsx', //不良原因小类
        failureTypeExcelBox: '不良类型导入模板.xlsx' //不良类型
      };
      const data = {
        originalName: exportKeyMap[key],
        attachType: 'EXCEL'
      };
      const res = await exprot({ data });
      const blob = new Blob([res.data]);
      const fileName = exportKeyMap[key];
      const link = document.createElement('a');
      link.download = fileName;
      link.style.display = 'none';
      link.href = URL.createObjectURL(blob);
      document.body.append(link);
      link.click();
      URL.revokeObjectURL(link.href);
      document.body.removeChild(link);
    },
    rowSave(form, done, loading) {
      form['dictType'] = this.getDictType(this.tabsIndex);
      add(form).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },

    rowUpdate(form, index, done, loading) {
      form['dictType'] = this.getDictType(this.tabsIndex);
      update(form).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    rowSubclassDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.failureSubclassData = this._filter(this.failureSubclassData, (item) => {
          return item.code !== row.code;
        });
      });
    },

    addRowUpdate(form, done) {
      done();
    },
    addRowrowSave(form, done) {
      done();
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      // this.$nextTick(() => {
      //   let dom = document.querySelectorAll('.el-dialog  .el-col-md-7');
      //   dom.forEach((el) => {
      //     el.style.width = '100%';
      //   });
      // });
      // getWorkstationRouteList().then(
      //   (res) => {
      //     this.workstationRouteList = this._get(res, 'data.data', []);
      //   },
      //   (error) => {
      //     this.workstationRouteList = [];
      //   }
      // );
      if (['edit', 'view'].includes(type)) {
        let paramsMap;
        if (this.tabsIndex === '1') {
          paramsMap = this.failureCodeModel;
        } else {
          paramsMap = this.repairCodeModel;
        }
        // getDetail(paramsMap.id).then((res) => {
        //   this.form = res.data.data;
        //   // this.failureCodeModel.workstationRoute = [];
        //   // if (this._get(res, 'data.data.workstationRouteId', '')) {
        //   //   let workstationRouteId = res.data.data.workstationRouteId.split(',');
        //   //   this._forEach(workstationRouteId, (item) => {
        //   //     this.failureCodeModel.workstationRoute.push(JSON.stringify(this._find(this.workstationRouteList, { id: item })));
        //   //   });
        //   // }
        // });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud && this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    async onLoad(page, params = {}) {
      this.loading = true;
      params['dictType'] = this.getDictType(this.tabsIndex);
      let PARAMS = Object.assign(params, this.query);
      getList(page.currentPage, page.pageSize, PARAMS).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        if (this.tabsIndex === '1') {
          this.failureCodeData = data.records;
          // this._forEach(result, (item) => {
          //   item.workstationRoute = [];
          //   if (item.workstationRouteId) {
          //     let workstationRouteIds = item.workstationRouteId.split(',');
          //     this.workstationRouteList.map((list) => {
          //       workstationRouteIds.map((id) => {
          //         if (list.id == id) {
          //           item.workstationRoute.push(list);
          //         }
          //       });
          //     });
          //     // this._forEach(workstationRouteId, (workstationRouteItem) => {
          //     //   item.workstationRoute.push(this._find(this.workstationRouteList, { id: workstationRouteItem }));
          //     // });
          //   } else {
          //     item.workstationRoute.push('');
          //   }
          // });
          // this.failureCodeData = result;
        } else if (this.tabsIndex === '2') {
          this.failureCauseData = data.records;
        } else if (this.tabsIndex === '3') {
          this.repairCodeData = data.records;
        } else if (this.tabsIndex === '4') {
          this.failureTypeData = data.records;
        }
        this.loading = false;
        this.selectionClear();
      });
    },
    onFailureSubclassLoad(page, params = {}) {
      this.loading = true;
      params['dictType'] = 'CAUSE';
      params['subType'] = 'SUB';
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.failureSubclassData = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    submit() {
      if (!this.isPassVaildator) {
        this.$message.error('请检查填写数据是否填写正确');
        return;
      }
      this.$refs.properties.validate((valid, done) => {
        if (valid) {
          let paramsMap = {
            id: this.failureCauseId,
            dictType: 'BAD_CAUSE',
            ...this.properties,
            subList: this.failureSubclassData
          };
          add(paramsMap).then(
            (res) => {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              done();
              this.showDialog = false;
              this.refreshChange();
            },
            (error) => {
              done();
              window.console.log(error);
            }
          );
        } else {
          done();
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleAddBtn() {
      if (this.tabsIndex === '2') {
        this.title = '添加不良原因';
        this.isNone = 'inline';
        this.failureCauseId = '';
        this.resetSubclass();
        this.editOrAddDis();
        this.showDialog = true;
      }
    },
    handleView(row) {
      this.title = '小类详情';
      this.isNone = 'none';
      this.resetSubclass();
      this.viewDis();
      this.showDialog = true;
      this.failureCauseId = row.id;
      this.failureCauseLoading = true;
      this.getMainAndSubDetail(row.id);
    },
    handleEdit(row) {
      this.title = '编辑不良原因';
      this.isNone = 'inline';
      this.resetSubclass();
      this.editOrAddDis();
      this.showDialog = true;
      this.failureCauseId = row.id;
      this.failureCauseLoading = true;
      this.getMainAndSubDetail(row.id);
    },
    /**
     * 获取大类和小类详情
     */
    getMainAndSubDetail(id) {
      getDetail(id)
        .then((res) => {
          const data = res.data.data;
          this.properties = {
            name: data.name,
            code: data.code
          };
          this.failureSubclassData = data.subList || [];
        })
        .finally(() => {
          this.failureCauseLoading = false;
        });
    },
    /**
     * tabs点击事件
     */
    handleTabClick(idx) {
      this.tabsIndex = idx;
      this.selectionList = [];
      this.query = { dictType: this.getDictType(this.tabsIndex) };
      // this.onLoad(this.page, {});
      this.$nextTick(() => {
        this.structuralSplit();
      });
    },
    /**
     * 添加行编辑
     */
    addCellRow() {
      this.$refs.failureSubclassCrud.rowCellAdd();
    },
    resetSubclass() {
      this.properties = {};
      this.failureSubclassData = [];
    },
    viewDis() {
      this.propertiesOption.column[0].disabled = true;
      this.propertiesOption.column[1].disabled = true;
      this.failureSubclassOption.menu = false;
    },
    editOrAddDis() {
      this.propertiesOption.column[0].disabled = false;
      this.propertiesOption.column[1].disabled = false;
      this.failureSubclassOption.menu = true;
    },
    /*
     *获取字典类型
     */
    getDictType(tabIdx) {
      switch (tabIdx) {
        case '1':
          return 'BAD_PHENOMENON';
        case '2':
          return 'BAD_CAUSE';
        case '3':
          return 'BAD_REPAIRE_CODE';
        case '4':
          return 'BAD_TYPE';
        default:
          break;
      }
    },
    failureCodeImport() {
      this.failureCodeExcelBox = true;
      this.failureCodeExcelForm = {};
    },
    uploadAfter(res, done, loading, column) {
      if (res.data && res.data.code != 200) {
        done();
      } else {
        this.failureCodeExcelBox = false;
        this.$message({
          type: 'success',
          message: '导入成功！'
        });
        this.onLoad(this.page);
        done();
      }
    },
    repairCodeImport() {
      this.repairCodeExcelBox = true;
      this.repairCodeExcelForm = {};
    },
    failureCauseImport() {
      this.failureCauseExcelBox = true;
      this.failureCauseExcelForm = {};
      this.failureCauseExcelForm2 = {};
    },
    failureTypeImport() {
      this.failureTypeExcelBox = true;
      this.failureTypeExcelForm = {};
    },
    async validatorMainCode(val) {
      try {
        const param = {
          code: val,
          dictType: 'BAD_CAUSE',
          subType: 'MAIN'
        };
        await checkCode(param);
        this.isPassVaildator = true;
      } catch (e) {
        this.isPassVaildator = false;
      }
    },
    async validatorSubCode(val) {
      try {
        const param = {
          code: val,
          dictType: 'BAD_CAUSE',
          subType: 'SUB'
        };
        await checkCode(param);
        this.isPassVaildator = true;
      } catch (e) {
        this.isPassVaildator = false;
      }
      console.log(val);
    },
    repairCodeUploadAfter(res, done, loading, column) {
      if (res.data && res.data.code != 200) {
        done();
      } else {
        this.repairCodeExcelBox = false;
        this.$message({
          type: 'success',
          message: '导入成功！'
        });
        this.onLoad(this.page);
        done();
      }
    },
    failureCauseUploadAfter(res, done, loading, column) {
      if (res.data && res.data.code != 200) {
        done();
      } else {
        this.failureCauseExcelBox = false;
        this.$message({
          type: 'success',
          message: '导入成功！'
        });
        this.onLoad(this.page);
        done();
      }
    },
    failureTypeUploadAfter(res, done, loading, column) {
      if (res.data && res.data.code != 200) {
        done();
      } else {
        this.failureTypeExcelBox = false;
        this.$message({
          type: 'success',
          message: '导入成功！'
        });
        this.onLoad(this.page);
        done();
      }
    },
    /*
     * 不良类型选择框
     */
    openFailureTypeCommonModal(title) {
      this.$refs.commonModalTemplate.showModal();
      this.modalName = 'failureType';
      this.tableOption = {
        modalTitle: '选择不良类型信息（双击进行选择）',
        url: '/api/mes-product/mro-dict/page?dictType=BAD_TYPE',
        isPage: true,
        index: true,
        searchBtn: true,
        titleInfo: title,
        rowSelectionType: 'single',
        searchLabelWidth: 100,
        columnDefs: [
          {
            label: '不良类型代码',
            prop: 'code',
            search: true
          },
          {
            label: '不良类型',
            prop: 'name',
            search: true
          }
        ]
      };
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .failure-title {
  padding-left: 5px;
  font-weight: 700;
  margin-bottom: 0;
  margin-top: 5px;
  border-left: 4px solid #4285a5;
  line-height: 22px;
}

::v-deep .el-dialog .el-input {
  width: 180px !important;
}
::v-deep .el-dialog__header {
  padding: 16px 24px;
  min-height: 20px;
  border-bottom: 1px solid #f0f0f0;
}

::v-deep .el-card__body {
  padding: 0;
}
::v-deep .failure_confing_crud {
  background-color: red !important;
  ::v-deep .dialogFooterClass {
    width: 70% !important;
  }
}
::v-deep .avue-view {
  background-color: blue !important;
}
</style>
